#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import redis

if __name__ == '__main__':
    r = redis.Redis(host = "127.0.0.1", port = 6379, password = "123456")
    # 一旦发现表里存储有某字段的键值对，再次修改会返回false
    # hash表只能完成基本数字类型的增加转换，其他字段无法修改
    print()
    print('hash 操作这里不再叙述，非常适合对象的各个字段存储，可以类比json结果')
    # HMSET runoobkey name "redis tutorial" description "redis basic commands for caching" likes 20 visitors 23000
    # HGETALL runoobkey  获取所有字段，key和value 都是其中的
    print(r.hgetall('runoobkey'))
    # 返回的是个字典，可以做字典解析
    print(type(r.hgetall('runoobkey')))
    # hdel 删除某个字段
    # hkeys *  获取所有
    # hmset  hmget 设置和获取字段数据，hmset 可以设置多个
    # hset 修改字段，修改成功返回1 修改失败返回0
    print(r.hset(name = 'runoobkey', key = 'description', value = '这里是做一段描述，不知道说点啥????'))
    print(type(r.hvals('runoobkey')))
    val = r.hvals('runoobkey')
    print(val)
    item0 = val[0]
    print(bytes.decode(item0))

    print()
    print(r.hset(name = 'monkey', key = 'color', value = 'yellow'))
    print(r.hset(name = 'monkey', key = 'height', value = '30cm'))
    print(r.hset(name = 'monkey', key = 'weight', value = '20kg'))
    print(r.hset(name = 'monkey', key = 'age', value = '1y'))
    print(r.hset(name = 'monkey', key = 'gender', value = 'male'))
    print(r.hsetnx(name = 'monkey', key = 'childrenCount', value = 20))
    print(r.hsetnx(name = 'monkey', key = 'legs', value = 22.454))
    print(r.hgetall('monkey'))
    print(r.hsetnx(name = 'monkey', key = 'gender', value = 'female'))
    print(r.hstrlen(name = 'monkey', key = 'gender'))
    # 自增成功后会返回该字段计算后的结果值
    print(r.hincrby(name = 'monkey', key = 'childrenCount', amount = 2))
    # 当增加数量为负数时，表示自减
    print(r.hincrby(name = 'monkey', key = 'childrenCount', amount = -2))
    # float自增和int自增类似，只不过是浮点型数据计算
    print(r.hincrbyfloat(name = 'monkey', key = 'legs', amount = 0.45))
    print(r.hincrbyfloat(name = 'monkey', key = 'legs', amount = -0.45))
    print(r.hgetall('monkey'))
    # hkeys  hvals 分别返回hash表的键名和数值
    print(r.hvals(name = 'monkey'))
    print(r.hkeys(name = 'monkey'))
